/*
 * @Author: yangzonglong
 * @Date: 2021-05-11 14:43:05
 * @version: v1.0.0
 * @Descripttion: 预览工作流视图
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-05-12 14:27:22
 * @Auditor: 
 */
import React, { useState, useCallback, useEffect } from 'react';
import { Modal } from 'antd';
import { units } from '@library';
import IconButton from './../iconButton/IconButton';
import CustomRenderer from './CustomRenderer';

const BpmnViewer = require('bpmn-js/dist/bpmn-viewer.production.min');

const getCustomRendererModule = (instancePath: string) => {
  CustomRenderer.prototype.getPath = () => {
    return instancePath || [];
  };
  return {
    __init__: ['customRenderer'],
    customRenderer: ['type', CustomRenderer]
  };
};

interface WfViewProps {
  workflowId?: string;
  bpmnContent?: string; // bpmnContent 如果存在 优化使用
  instancePath?: string; // 流程实例已走线路
  flat?: boolean; // 为true时 则直接显示工作流视图 不通过btn
}

const WfViewPage =  ({ workflowId, instancePath, bpmnContent: defBpmnContent, flat }: WfViewProps) => {
  const [bpmnContent, setBpmnContent] = useState<string>('');
  const [visible, setVisible] = useState(false);
  const onCancel = useCallback(() => setVisible(false), []);
  const onShow = useCallback(() => setVisible(true), []);

  useEffect(() => {
    if (defBpmnContent) return setBpmnContent(defBpmnContent);
    if (!workflowId) return;

    units.serverLoading('/bk/api/workflow/WorkFlowHead/findOne', {
      where: { id: workflowId }
    }).then(result => {
      setBpmnContent(result?.bpmnContent);
    });
  }, [workflowId, visible, defBpmnContent]);

  useEffect(() => {
    if (!bpmnContent) return;
    if (!flat && !visible) return;

    const viewer = new BpmnViewer({
      container: '#canvas',
      height: 550,
      additionalModules: instancePath ? [getCustomRendererModule(instancePath)] : []
    });

    viewer.importXML(bpmnContent).then((res) => {
      viewer.get('canvas').zoom('fit-viewport', 'auto');
    }).catch(err => {
      console.error(err);
    });

    return () => {
      viewer.destroy();
    };
  }, [bpmnContent, visible, instancePath, flat]);

  return (
    <>
      {!flat && <IconButton onClick={onShow} text={window.$app.t('workflowView')} icon='icon' />}
      {flat && <div id="canvas" />}
      <Modal
        centered
        title={window.$app.t('workflowView')}
        width={1400}
        onCancel={onCancel}
        visible={visible}
        footer={null}>
        <div id="canvas" />
      </Modal>
    </>
  );
};

export default WfViewPage
